package com.simulation.web.controller.tool;

import com.alibaba.fastjson2.JSONObject;
import com.simulation.common.core.controller.BaseController;
import com.simulation.common.core.domain.AjaxResult;
import com.simulation.common.core.domain.entity.SysUser;
import com.simulation.common.core.domain.model.LoginUser;
import com.simulation.common.core.redis.RedisCache;
import com.simulation.common.utils.CoderUtils;
import com.simulation.common.utils.StringUtils;
import com.simulation.framework.web.domain.server.Sys;
import com.simulation.system.service.ISysUserService;
import com.simulation.common.dto.CodeWorkspaceDTO;
import com.simulation.web.domain.TechPost;
import com.simulation.web.service.PostService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangxn
 * @date 2024/12/16  21:11
 */
@RestController
@RequestMapping("/coder/tool")
public class CoderController  extends BaseController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private PostService postService;

    @Resource
    private RedisCache redisCache;

    @ApiOperation("登录Coder")
    @GetMapping("/login-code")
    @PermitAll
    public void login(@RequestParam("userName") String userName, HttpServletResponse response) throws IOException {
        // 我启动coder
        SysUser sysUser = sysUserService.selectOneUserByUserName(userName);
        CoderUtils.changeStatusWorkspace(sysUser.getRemark(), "start");

        String result = CoderUtils.login(sysUser.getEmail(), sysUser.getPassno());
        String token = JSONObject.parse(result).getString("session_token");
        // 设置一个cookie
        Cookie myCookie = new Cookie("coder_session_token", token);
        myCookie.setMaxAge(3600); // 设置cookie有效期为1小时
        myCookie.setPath("/"); // 设置cookie的有效路径
        myCookie.setDomain(".coder.yanzhiwei.top");
        response.addCookie(myCookie);
        // 重定向到其他地址
        response.setStatus(HttpServletResponse.SC_FOUND);
//        response.setHeader("Location", "https://coder.yanzhiwei.top:31443/@"+userName+"/"+userName+".main/apps/code-server/");
        response.sendRedirect("https://coder.yanzhiwei.top:31443/@"+userName+"/"+userName+".main/apps/code-server/?folder=/home/ubuntu/develop");
    }

    @ApiOperation("登录Codertoken")
    @GetMapping("/login-code-token")
    @PermitAll
    public AjaxResult loginToken(@RequestParam("userName") String userName, HttpServletResponse response) throws IOException {
        // 我启动coder
        SysUser sysUser = sysUserService.selectOneUserByUserName(userName);
        String token = "";
        if (Objects.isNull(redisCache.getCacheObject(sysUser.getUserName()))) {
//            CoderUtils.changeStatusWorkspace(sysUser.getRemark(), "start");
            String result = CoderUtils.login(sysUser.getEmail(), sysUser.getPassno());
            token = JSONObject.parse(result).getString("session_token");
            redisCache.setCacheObject(sysUser.getUserName(), token,10*60, TimeUnit.SECONDS);
        } else {
            token = redisCache.getCacheObject(sysUser.getUserName()).toString();
        }
        return AjaxResult.success("操作成功",token);
    }


    @ApiOperation("创建项目空间")
    @PostMapping("/createWorkspace")
    @PermitAll
    public AjaxResult createWorkspace(@RequestBody CodeWorkspaceDTO codeWorkspaceDTO) {
        // 我启动coder
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = sysUserService.selectUserPassnoById(loginUser.getUserId());
        codeWorkspaceDTO.setUserId(sysUser.getCoderUserId());
        String result = CoderUtils.createWorkspace(codeWorkspaceDTO,sysUser.getUserName(),sysUser.getPassno());
        if (StringUtils.isNotEmpty(result)) {
            postService.updatePostWorkspaceId(codeWorkspaceDTO.getProjectId(), result, codeWorkspaceDTO.getGitRepo(),codeWorkspaceDTO.getEnvironment());
        }
        return AjaxResult.success("操作成功", result);
    }


    @ApiOperation("启动项目空间")
    @GetMapping("/startWorkspace")
    @PermitAll
    public AjaxResult startWorkspace(@RequestParam("workspaceId") String workspaceId,@RequestParam("status") String status) {
        // 启动coder
        String result = CoderUtils.changeStatusWorkspace(workspaceId, status);
        return AjaxResult.success("操作成功",result);
    }


    @ApiOperation("项目空间状态")
    @GetMapping("/getWorkspaceStatus")
    @PermitAll
    public AjaxResult getWorkspaceStatus(@RequestParam("workspaceName") String workspaceName) {
        // 启动coder
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = sysUserService.selectUserPassnoById(loginUser.getUserId());
        String result = CoderUtils.getStatusWorkspace(workspaceName, sysUser.getCoderUserId());
        return AjaxResult.success("操作成功",result);
    }





}
